package com.leyou.item.controller;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("brand")
public class BrandController {

    @Autowired
    BrandService bs;

    @RequestMapping("page")
    public ResponseEntity<PageResult<Brand>> page(
            @RequestParam(name = "key")String key,
            @RequestParam(name = "page",defaultValue = "1")Integer page,
            @RequestParam(name = "rows",defaultValue = "5")Integer rows,
            @RequestParam(name = "sortBy")String sortBy,
            @RequestParam(name = "desc")Boolean desc
    ){
        PageResult<Brand> pageResult = bs.queryByManyCase(key,page,rows,sortBy,desc);

        if (CollectionUtils.isEmpty(pageResult.getItems())){
            // 404
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(pageResult);

    }

    /*
    List<Integer> cids 传过来的形式是  1，2，3，4
    springMVC会将这种形式，自动转化为  List集合的形式
     */
    // api.leyou.com/api/item/brand
    @PostMapping
    public ResponseEntity<Void> add(Brand brand, @RequestParam("cids") List<Integer> cids){

        bs.insertBrand(brand,cids);

        // 只需要返回成功就行了，而不需要进行数据的响应
        return ResponseEntity.ok().build();

    }

    @PutMapping
    public ResponseEntity<Void> update(Brand brand, @RequestParam("cids") List<Integer> cids){

        bs.update(brand,cids);

        // 只需要返回成功就行了，而不需要进行数据的响应
        return ResponseEntity.ok().build();

    }

    @GetMapping("cid/{cid}")
    public ResponseEntity<List<Brand>> getBrandByCid(@PathVariable("cid") Integer cid){

        List<Brand> list = bs.getBrandByCid(cid);
        if (CollectionUtils.isEmpty(list)){
            // 404
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(list);

    }

    @GetMapping("{brandId}")
    public ResponseEntity<Brand> getBrandByBrandId(@PathVariable("brandId")Long brandId){
        Brand brand = bs.getBrandByBrandId(brandId);

        return ResponseEntity.ok(brand);
    }



}
